<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>播放器</title>
		<!--    <script src="./vconsole.js"></script>-->
		<script src="./jessibuca-pro/jessibuca-pro.js"></script>
		<link rel="stylesheet" href="./player.css">
		<style>
			.container-shell:before {
				content: "";
			}
		</style>
	</head>
	<body class="page">
		<div class="root">
			<div class="container-shell">
				<div id="container"></div>
			</div>
		</div>
	</body>
	<script src="./player.js"></script>
	<!-- uni 的 SDK -->
	<script src="./uni.webview.1.5.5.js"></script>
	<script type="text/javascript">
		var userAgent = navigator.userAgent;
		console.log("userAgent");
		console.log(userAgent);
		if (userAgent.indexOf('AlipayClient') > -1) {
			// 支付宝小程序的 JS-SDK 防止 404 需要动态加载，如果不需要兼容支付宝小程序，则无需引用此 JS 文件。
			document.writeln('<script src="https://appx/web-view.min.js"' + '>' + '<' + '/' + 'script>');
		} else if (/QQ/i.test(userAgent) && /miniProgram/i.test(userAgent)) {
			// QQ 小程序
			document.write(
				'<script type="text/javascript" src="https://qqq.gtimg.cn/miniprogram/webview_jssdk/qqjssdk-1.0.0.js"><\/script>'
			);
		} else if (/miniProgram/i.test(userAgent) && /micromessenger/i.test(userAgent)) {
			console.log("微信小程序 JS-SDK");
			// 微信小程序 JS-SDK 如果不需要兼容微信小程序，则无需引用此 JS 文件。
			document.write('<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"><\/script>');
			wx.miniProgram.getEnv(function(res) {
				console.log(res.miniprogram) // true
			}) // true
		} else if (/toutiaomicroapp/i.test(userAgent)) {
			// 头条小程序 JS-SDK 如果不需要兼容头条小程序，则无需引用此 JS 文件。
			document.write(
				'<script type="text/javascript" src="https://s3.pstatp.com/toutiao/tmajssdk/jssdk-1.0.1.js"><\/script>');
		} else if (/swan/i.test(userAgent)) {
			// 百度小程序 JS-SDK 如果不需要兼容百度小程序，则无需引用此 JS 文件。
			document.write(
				'<script type="text/javascript" src="https://b.bdstatic.com/searchbox/icms/searchbox/js/swan-2.0.18.js"><\/script>'
			);
		} else if (/quickapp/i.test(userAgent)) {
			// quickapp
			document.write('<script type="text/javascript" src="https://quickapp/jssdk.webview.min.js"><\/script>');
		}

		if (!/toutiaomicroapp/i.test(userAgent)) {
			console.log("webview post-message-section");
			//document.querySelector('.post-message-section').style.visibility = 'visible';
		}
	</script>

	<script type="text/javascript">
		var container = document.getElementById('container');
		var showOperateBtns = true; // 是否显示按钮
		var jessibuca = null;
		var rotate = 90;
		var playUrl = null;
        var playTpye = null;
		console.log("jessibuca webview");
		var data = getQuery('data');
		if (data != null) {
			console.log(data);
			var json = JSON.parse(data);
            playTpye = json.type;
			playurl(json, json.playUrl);
		}

		function getQuery(name) {
			let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
			let r = window.location.search.substr(1).match(reg);
			if (r != null) {
				return decodeURIComponent(r[2]);
			}
			return null;
		}

		function replay() {
			if (jessibuca != null) {
				jessibuca.destroy();
			}
			create()
		}

		function setplayUrl(url) {
			console.log("set playUrl:" + url);
			playUrl = url;
		}

		function playurl(json, url) {
			setplayUrl(url);
			replay();
			if (playTpye === "play") {
				play(url);
			} else if (playTpye === "playback") {
				playback(url, json.playTimes);
			}
		}

		function create() {
			console.log("jessibuca create");
			jessibuca = new JessibucaPro({
				container: container,
				videoBuffer: 0.2, // 缓存时长
				decoder: './jessibuca-pro/decoder-pro.js',
				useSIMD: true,
				//useWCS: true,
				//useMSE: true,
				isResize: false,
				isFullResize: false,
				forceNoOffscreen: true,
				useWebFullScreen: true,
				useVideoRender: true,
				useCanvasRender: false,
				isNotMute: false,
				text: "",
				loadingText: "加载中",
				debug: false,
				debugLevel: 'debug',
				showBandwidth: showOperateBtns, // 显示网速
				operateBtns: {
					fullscreen: showOperateBtns,
					screenshot: showOperateBtns,
					play: showOperateBtns,
					audio: showOperateBtns,
					fullscreenFn: function() {
						console.log('fullscreenFn');
						jessibuca.setFullscreen(true);
					},
					fullscreenExitFn: function() {
						console.log('fullscreenExitFn');
						jessibuca.setFullscreen(false);
						jessibuca.setRotate(0);
						rotate = 90;
					},
				},
				extendOperateBtns: [{
					name: '横竖屏切换',
					index: 3,
					icon: '',
					iconHover: '',
					iconTitle: '横竖屏切换',
					click: () => {
						console.log('点击了横竖屏切换');
						uni.postMessage({
							data: {
								action: '点击了横竖屏切换'
							}
						});
						jessibuca.setRotate(rotate);
						if (rotate == 90) {
							rotate = 0
						} else if (rotate == 0) {
							rotate = 90
						}
					}
				}, ],

			}, );
			console.log("jessibuca create ");
            let pre = 0
            let cur = 0
            jessibuca.on('timeUpdate', function(ts) {
                cur = parseInt(ts / 60000)
                if (pre !== cur) {
                    pre++
                }
            })

            if (playTpye === "playback") {
                jessibuca.on('playbackSeek', (timeObj) => {
                    console.log('playbackSeek!')
                    seekPlay(timeObj)
                })
            }
			jessibuca.on('error', function(error) {
				console.log('error')
				console.log(error)
			})
			jessibuca.on("fetchError", function(data) {
				console.log('fetchError:', data)
			})
			jessibuca.on("start", function() {
				console.log('start render')
			})
			jessibuca.on("play", function(flag) {
				console.log('play')
			})
			jessibuca.on('crashLog', (data) => {
				console.log('crashLog is', data);
			})
			jessibuca.on("fullscreen", function(flag) {
				console.log('is fullscreen', flag)
			})
			jessibuca.on("webFullscreen", function(flag) {
				console.log('is webFullscreen', flag)
			})
			console.log("jessibuca create end");
		}

		function seekPlay(timeObj) {
			uni.postMessage({
				data: {
					action: 'seekPlay',
					msg: timeObj
				}
			});
		}

		function play(url) {
			console.log("play");
			console.log(url);
			if (url) {
				const status = jessibuca.getStatus();
				console.log(status);
				jessibuca.play(url).then(() => {
					console.log('play success')
				}).catch((e) => {
					console.log('play error', e)
				})
			}
		}

		function playback(url, times) {
			if (url) {
				jessibuca.playback(url, {
					playList: times,
					fps: 20, //FPS（定频(本地设置)生效）
					showControl: true,
					showRateBtn: true,
					isUseFpsRender: true, // 是否使用固定的fps渲染，如果设置的fps小于流推过来的，会造成内存堆积甚至溢出
					isCacheBeforeDecodeForFpsRender: false, // rfs渲染时，是否在解码前缓存数据
					supportWheel: true, // 是否支持滚动轴切换精度。
					rateConfig: [
						{ label: '正常', value: 1 },
						{ label: '2倍', value: 2 },
						{ label: '4倍', value: 4 },
						{ label: '8倍', value: 8 },
					],
				})
			}
		}
		window.pause = function() {
			console.log("pause")
			jessibuca.pause()
		}
		window.setPlaybackStartTime = function(curTime) {
			console.log("setPlaybackStartTime")
			jessibuca.setPlaybackStartTime(curTime)
		}
		window.screenshot = function() {
			console.log("screenshot")
			const timestamp = new Date().getTime();
			const filename = this.deviceId + this.channelId + '-' + timestamp;
			jessibuca.screenshot(filename, "png", 0.92);
		}
		window.startRecord = function() {
			console.log("startRecord")
			const timestamp = new Date().getTime();
			const filename = this.deviceId + this.channelId + '-' + timestamp;
			jessibuca.startRecord(filename);
		}
		window.stopRecordAndSave = function() {
			console.log("stopRecordAndSave")
			jessibuca.stopRecordAndSave();
		}
		document.addEventListener("UniAppJSBridgeReady", function() {
			console.log("UniAppJSBridgeReady ready");
			uni.postMessage({
				data: {
					action: 'UniAppJSBridgeReady'
				}
			});

			uni.getEnv(function(res) {
				console.log('当前环境：' + JSON.stringify(res));
			});
			// uni.switchTab({
			//     url: '/pages/tabBar/API/API'
			// });
			// uni.reLaunch({
			//     url: '/pages/tabBar/component/component'
			// });
			// uni.navigateBack({
			//     delta: 1
			// });
			// uni[action]({
			//     url: '/pages/component/button/button'
			// });

		})
		//微信小程序
		function ready() {
			console.log(window.__wxjs_environment === 'miniprogram')
		}

		if (!window.WeixinJSBridge || !WeixinJSBridge.invoke) {
			document.addEventListener('WeixinJSBridgeReady', ready, false)
		} else {
			ready()
		}
        console.log("οnbefοreunlοad");
		window.οnbefοreunlοad = function() {
			alert("===οnbefοreunlοad===");
			if (event.clientX > document.body.clientWidth && event.clientY < 0 || event.altKey) {
				alert("你关闭了浏览器");
				jessibuca.destroy();
			} else {
				alert("你正在刷新页面");
				replay();
			}
		}
	</script>


</html>
